﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using PhilWicklund.com.SiteCreationWorkflow.Data;

namespace PhilWicklund.com.SiteCreationWorkflow.Utilities
{
	public static class WorkflowItemFactory
	{
		internal static void CreateNewItem(SPWeb newWeb)
		{
			//retrieve settings
			WorkflowSettings settings = WorkflowSettings.GetSettings(
				newWeb.Site.RootWeb.Url
				);
			 
			//insert list item
			SPWeb settingsWeb = newWeb.Site.RootWeb;
			settingsWeb.AllowUnsafeUpdates = true;
			SPList list;
			try
			{
				list = settingsWeb.Lists[settings.listName];
			}
			catch (Exception)
			{
				throw new Exception("ERROR: The site approval requests list has not bee instanciated on the root web or the list name in the workflow settings is incorect.");
			}
			SPListItem item = list.Items.Add();
			item["Title"] = "New site requested by " + newWeb.Author.Name;
			item["Proposed Site"] = newWeb.Url + ", " + newWeb.Title;
			item["Creator Email"] = newWeb.Author.Email;
			item["Web ID"] = newWeb.ID.ToString();
			item.Update();
			settingsWeb.AllowUnsafeUpdates = false;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="web">Web that contains the site approval list and workflow properties for a given site collection.</param>
		/// <param name="siteUrl"></param>
		/// <param name="justification"></param>
		/// <param name="contactMe"></param>
		public static void SiteJustificationUpdate(string webUrl, string justification)
		{
			SPSecurity.RunWithElevatedPrivileges(delegate()
			{
				using (SPSite site = new SPSite(webUrl))
				{
					string relativeWebUrl = "";
					if (site.Url != webUrl) // NOT Root Web
						relativeWebUrl = webUrl.Substring(site.Url.Length + 1);
					using (SPWeb web = site.OpenWeb(relativeWebUrl))
					{
						SPWebApplication webApp = web.Site.WebApplication;
						webApp.FormDigestSettings.Enabled = false;
						web.AllowUnsafeUpdates = true;
						WorkflowSettings settings = WorkflowSettings.GetSettings(web.Site.RootWeb.Url);
						
						SPList list = web.Site.RootWeb.Lists[settings.listName];
						
						SPQuery query = new SPQuery();

						StringBuilder queryString = new StringBuilder();
						queryString.Append("<Where>");
						queryString.Append("   <Eq>");
						queryString.Append("      <FieldRef Name=\"" + list.Fields["Web ID"].InternalName + "\" />");
						queryString.Append("      <Value Type=\"Text\">" + web.ID.ToString() + "</Value>");
						queryString.Append("   </Eq>");
						queryString.Append("</Where>");

						query.Query = queryString.ToString();
						SPListItemCollection items = list.GetItems(query);

						if (items.Count == 0)
							throw new Exception("ERROR: this web was not found in the site approval request list.");

						SPListItem item = items[0];
						// TODO: if (items.Count > 1)

						item["Purpose for Site"] = justification;
						item.Update();

						web.AllowUnsafeUpdates = false;
						webApp.FormDigestSettings.Enabled = true;
					}
				}
			});
		}
	}
}
